package com.lingshi.shopping_file_service.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.lingshi.common.service.IFileService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Value;

import java.io.ByteArrayInputStream;
import java.util.List;


@DubboService
public class FileServiceImpl implements IFileService {
    @Value("${oss.upload.endpoint}")
    private String endpoint;

    @Value("${oss.upload.accessKey}")
    private String accessKeyId;

    @Value("${oss.upload.secretKey}")
    private String accessKeySecret;
    @Value("${oss.upload.bucket}")
    private String bucketName;

    @Value("${oss.upload.serverUrl}")
    private String serverUrl;


    public OSS initOss() {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        return ossClient;
    }
    @Override
    public String uploadImage(byte[] data, String fileName) {
        OSS oss = initOss();
        try {
            //获取文件名后缀
            String extName = FileNameUtil.extName(fileName);

            //生成新的随机文件名称
            String newFileName = RandomUtil.randomString(20);

            newFileName = newFileName + StrUtil.DOT + extName;

            ByteArrayInputStream inputStream = new ByteArrayInputStream(data);

            //上传oss文件
            oss.putObject(bucketName, newFileName, inputStream);

            //拼接完整的文件服务地址
            return serverUrl + StrUtil.SLASH + newFileName;

        } finally {
            oss.shutdown();
        }
    }

    @Override
    public void delete(String filePath) {
        OSS oss = initOss();
        try {
            List<String> list = StrUtil.split(filePath, "/");
            String fileName = CollUtil.getLast(list);
            oss.deleteObject(bucketName,fileName);
        } finally {
            oss.shutdown();
        }
    }
}
